// booleans_zhijiao/search/search.js
let app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    friendsList: [],
    notFriendsList: [],
    hiddenmodalput: true,
    max:50,
    currentWordNumber:0,
    searchText: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取上一个页面的page对象，使用上个页面的方法
    let pages = getCurrentPages()
    this.prePage = pages[pages.length - 2]
    console.log(this.prePage)
    this.nickname = wx.getStorageSync('userInfo').wxInfo.nickName
  },
  onShareAppMessage: function () {
    return {
      title: `${this.nickname}邀你吐槽他`,
      path: `booleans_zhijiao/index/index?id=${app.globalData.i_id}`,
      imageUrl: "../../images/sample.jpg"
    }
  },
  searchInput (e) {
    let that = this
    // console.log(e.detail.value)
    // 防抖动处理
    that.setData({
      searchText: e.detail.value
    })
    if (that.timer) {
      clearTimeout(that.timer)
    }
    that.timer = setTimeout(() => {
      that._search(e.detail.value).then((res) => {
        console.log(res.data.data)
        that.setData({
          friendsList: res.data.data.friends,
          notFriendsList: res.data.data.notFriends
        })
      }).catch((res) => {
        console.log(res)
      })
    }, 800)
  },
  toMessageInput (e) {
    console.log(e.currentTarget.dataset.id)
    this.prePage.scrollTo(`id${e.currentTarget.dataset.id}`)
    this.prePage.messageInput(e)
    wx.navigateBack({})
  },
  addFriend (e) {
    console.log(e.currentTarget.dataset.id)
    this._addFriend(e.currentTarget.dataset.id).then((res) => {
      console.log(res.data.message)
      wx.showToast({
        title: res.data.message,
        showCancel: false,
        duration: 2000,
        success: () => {
          setTimeout(() => {
            this.prePage._getFriendsList().then((res) => {
              this.prePage.setData({list: this.prePage._normalizeList(res.data.data)})
              this.prePage.scrollTo(`id${e.currentTarget.dataset.id}`)
            })
            wx.navigateBack({})
          }, 2000)
        }
      })
    })
  },
  _search (content) {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/searchUser',
        data: {
          key_word: content
        },
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
  },
  _addFriend (id) {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/addfriends',
        data: {
          friend_id: id
        },
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res)
        }
      })
    })
  }
})
